import bcrypt
import json
from datetime import datetime
from typing import Dict, Any

def hash_password(password: str) -> str:
    """密码加密"""
    return bcrypt.hashpw(password.encode('utf-8'), bcrypt.gensalt()).decode('utf-8')

def verify_password(password: str, hashed: str) -> bool:
    """密码验证"""
    return bcrypt.checkpw(password.encode('utf-8'), hashed.encode('utf-8'))

def parse_datetime(date_string: str) -> datetime:
    """解析日期时间字符串"""
    try:
        return datetime.fromisoformat(date_string.replace('Z', '+00:00'))
    except:
        return datetime.utcnow()

def validate_json_string(json_string: str) -> bool:
    """验证JSON字符串是否有效"""
    try:
        json.loads(json_string)
        return True
    except:
        return False

def safe_json_loads(json_string: str, default=None):
    """安全的JSON解析"""
    try:
        return json.loads(json_string)
    except:
        return default

def format_response(data: Any = None, message: str = "success", code: int = 200) -> Dict:
    """格式化响应"""
    return {
        "code": code,
        "message": message,
        "data": data
    }

def validate_problem_type(problem_type: str) -> bool:
    """验证题目类型"""
    valid_types = ['choice', 'blank', 'code', 'short']
    return problem_type in valid_types

def validate_submission_status(status: str) -> bool:
    """验证提交状态"""
    valid_statuses = ['Pending', 'AC', 'WA', 'RE', 'TLE']
    return status in valid_statuses
